package com.tmsps.auto.action.cp;

import org.ne.framework.data.util.ChkTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.tmsps.auto.action.BaseAction;
import com.tmsps.auto.action.Tip.Type;
import com.tmsps.auto.conf.SESSION_VAL;
import com.tmsps.auto.model.t_admin;
import com.tmsps.auto.service.base.AdminService;
import com.tmsps.auto.utils.MD5;

@Controller
@Scope("prototype")
public class LoginAction extends BaseAction {
	@Autowired
	private AdminService adminService;

	@RequestMapping("logincp")
	public ModelAndView AdminLogin() {
		log.debug("欢迎使用后台管理系统");
		ModelAndView mv = new ModelAndView("/admin_cp/login");
		setTipMsg("欢迎登录");
		mv.addObject("tip", tip);
		return mv;
	}

	@RequestMapping(value = "adminLogin.htm", method = RequestMethod.POST)
	public ModelAndView doAdminLogin(String m_name, String m_password) {
		ModelAndView mv = new ModelAndView();
		if (ChkTools.isNull(m_name) || ChkTools.isNull(m_password)) {
			mv.setViewName("/admin_cp/login");
			log.error("用户名密码不能为空");
			setTipMsg("用户名密码不能为空", Type.error);
		}
		t_admin ta = adminService.adminLoginCheck(m_name, MD5.md5(m_password));
		if (ChkTools.isNull(ta)) {
			mv.setViewName("/admin_cp/login");
			setTipMsg("用户名密码不匹配", Type.error);
		} else {
			log.info("欢迎管理员:" + ta.getM_name() + "{" + ta.getM_nickname() + "}");
			WebUtils.setSessionAttribute(request, SESSION_VAL.ADMIN_INFO, ta);
			mv.setViewName("redirect:/cp/main.htm");
		}
		mv.addObject("tip", tip);
		return mv;
	}

	@RequestMapping(value = "/cp/logout.htm", method = RequestMethod.GET)
	public ModelAndView logout() {
		t_admin ta = (t_admin) WebUtils.getSessionAttribute(request,
				SESSION_VAL.ADMIN_INFO);
		log.info(ta.getM_nickname() + "退出管理系统！");
		setTipMsg("你已经退出管理系统,感谢使用!");
		ModelAndView mv = new ModelAndView("/admin_cp/login");
		mv.addObject("tip", tip);
		request.getSession().invalidate();
		return mv;
	}

}
